<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\model\user\LevelOrder;
use app\common\model\user\PerkGrant;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 现金补贴发放记录
 *
 * @icon fa fa-circle-o
 */
class Grant extends Backend
{

    /**
     * 模型对象
     * @var
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new PerkGrant();
        $this->view->assign("typeDataList", $this->model->getTypeDataList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {

                $row->nicknames=$this->model->getEnzdAttr($row,$row);
                //$row->getRelation('goods')->visible(['title']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }



    //新增 发放现金补贴
    public function grant()
    {
        if (false === $this->request->isPost()) {
            $ids="";
            if($this->request->param("ids") && !empty($this->request->param("ids"))){
                $ids=$this->request->param("ids");
            }
            $this->assign("ids",$ids);
            return $this->view->fetch("user/user/grant");
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $data = [
            ['user_id', 'require', '请选择用户'],
            ['money', 'require', '请输入发放金额'],
            ['day', 'require', '请输入发放天数'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error('提交失败：' . $validate->getError());
        }
        $result = false;
        Db::startTrans();
        try {
            $config = get_addon_config('wanlshop');
            $radio_use_day = $config["subsidy"]["radio_use_day"] ?? 10;//有效期天数
            $end_day=ceil($params["money"]/$params["day"]);
            $date = strtotime('+'.($radio_use_day+$end_day+1).' day',time());
            $daily_money=bcdiv($params["money"],$params["day"],2);
            $grant_id=PerkGrant::insertGetId([
                "user_ids"=>$params["user_id"],
                "remarks"=>"平台发放现金补贴",
                "subsidy_money"=>$params["money"],
                "residue_money"=>$params["money"],
                "daily_money"=>$daily_money,//每日到账x元
                "end_granttime"=>$date,
                "createtime"=>time(),
                "day"=>$params["day"],
            ]);
            $ids=explode(",",$params["user_id"]);
            $order_data=[];
            foreach ($ids as $k=>$v){
                $order_data[$k]=[
                    "user_id"=>$v,
                    "state"=>2,
                    "level_id"=>0,
                    "order_no"=>0,
                    "level_details"=>"",
                    "subsidy_money"=>$params["money"],
                    "residue_money"=>$params["money"],
                    "daily_money"=>$daily_money,//每日到账x元
                    "end_granttime"=>$date,
                    "goods_id"=>0,
                    "agent_id"=>0,
                    "createtime"=>time(),
                    "type"=>1,
                    "grant_id" => $grant_id,
                ];
            }
            if(!empty($order_data)){
                $orderModel = new LevelOrder();
                $result=$orderModel->saveAll($order_data);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
}
